/*
Copyright (c) 2014 Sanjay Dasgupta (sanjay.dasgupta@gmail.com)
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package ipex

import scala.collection.mutable
import scala.xml.{Elem, XML}

object MemData {

  val labelMap = mutable.Map.empty[String, Pair[List[String], List[String]]]
  val ruleToLabels = mutable.Map.empty[String, List[String]].withDefaultValue(Nil)
  val sectionToLabels = mutable.Map.empty[String, List[String]].withDefaultValue(Nil)
  val ruleToForms = mutable.Map.empty[String, List[String]].withDefaultValue(Nil)

  val labelRows = XML.load(ClassLoader.getSystemResourceAsStream("resources/labels.html")).
    child(0).child(0).child.tail.filter(_.isInstanceOf[Elem]).map(_.asInstanceOf[Elem])
  labelRows.foreach {
    case Elem(_, _, _, _, label, sectionList, ruleList) =>
      val theLabel = label.text.trim
      val theSections = sectionList.text.trim match {
        case "" => Nil
        case sl => sl.split(",").map(_.trim).toList
      }
      val theRules = ruleList.text.trim match {
        case "" => Nil
        case rl => rl.split(",").map(_.trim).toList
      }
      labelMap(theLabel) = Pair(theSections, theRules)
      for (s <- theSections) {
        val ss = if (s.charAt(0).isDigit) s else s.substring(1)
        if (sectionToLabels.contains(ss))
          sectionToLabels(ss) ::= theLabel
        else
          sectionToLabels(ss) = List(theLabel)
      }
      for (r <- theRules) {
        val rr = if (r.charAt(0).isDigit) r else r.substring(1)
        if (ruleToLabels.contains(rr))
          ruleToLabels(rr) ::= theLabel
        else
          ruleToLabels(rr) = List(theLabel)
      }
  }

  val sectionRows = XML.load(ClassLoader.getSystemResourceAsStream("resources/sections.html")).
    child(0).child(0).child.tail.filter(_.isInstanceOf[Elem]).map(_.asInstanceOf[Elem])
  val sections = sectionRows.map {
    case Elem(_, _, _, _, n, title, text, chNo, labels) =>
      K(n.text, if (title.text.trim.nonEmpty) Some(title.text.trim) else None,
        if (text.text.trim.nonEmpty) Some(text.text.trim) else None, chNo.text)
  }

  val ruleRows = XML.load(ClassLoader.getSystemResourceAsStream("resources/rules.html")).
    child(0).child(0).child.tail.filter(_.isInstanceOf[Elem]).map(_.asInstanceOf[Elem])
  val rules = ruleRows.map {
    case Elem(_, _, _, _, n, title, text, chNo, sectNos, labels) =>
      K(n.text, if (title.text.trim.nonEmpty) Some(title.text.trim) else None,
        if (text.text.trim.nonEmpty) Some(text.text.trim) else None, chNo.text)
  }

  val formRows = XML.load(ClassLoader.getSystemResourceAsStream("resources/forms.html"))/*html*/.
    child(0)/*body*/.child(0)/*table*/.child.tail/*data*/.filter(_.isInstanceOf[Elem]).map(_.asInstanceOf[Elem])
  val forms = formRows.foreach {
    case Elem(_, _, _, _, formNo, sectNos, ruleNos) =>
      for (r <- ruleNos.text.split(",").flatMap(MemData.ancestors)) {
        if (ruleToForms.contains(r))
          ruleToForms(r) ::= formNo.text
        else
          ruleToForms(r) = List(formNo.text)
      }
  }

  val sectionRules = ruleRows.map(e => Pair(e.child(0).text.trim, e.child(4).text.trim)).filter(_._2.nonEmpty).
    map(p => (p._1, p._2.split(","))).flatMap(p => p._2.map(t => (t, p._1)))

  def relatedSectionNumbers(ruleNbr: String): Seq[String] =
    if (ruleToSections.contains(ruleNbr)) ruleToSections(ruleNbr) else Nil

  def relatedRuleNumbers(sectionNbr: String): Seq[String] =
    if (sectionToRules.contains(sectionNbr)) sectionToRules(sectionNbr) else Nil

  def searchSections(searchText: String): Seq[K] = {
    def matches(str: String): Boolean = {
      val orAnds: Array[Array[String]] =
        searchText.split("\\s+(?i:OR)\\s+").map(_.split("\\s+(?i:AND)\\s+").map(s => s".*(?i:${s.trim}).*"))
      orAnds.exists(_.forall(str.matches))
    }
    sections.filter({
      case K(_, Some(title), Some(text), _) if matches(text) || matches(title) => true
      case K(_, None, Some(text), _) if matches(text) => true
      case K(_, Some(title), None, _) if matches(title) => true
      case _ => false
    })
  }

  def searchRules(searchText: String): Seq[K] = {
    def matches(str: String): Boolean = {
      val orAnds: Array[Array[String]] =
        searchText.split("\\s+(?i:OR)\\s+").map(_.split("\\s+(?i:AND)\\s+").map(s => s".*(?i:${s.trim}).*"))
      orAnds.exists(_.forall(str.matches))
    }
    rules.filter({
      case K(_, Some(title), Some(text), _) if matches(text) || matches(title) => true
      case K(_, None, Some(text), _) if matches(text) => true
      case K(_, Some(title), None, _) if matches(title) => true
      case _ => false
    })
  }

  def sectionsTree(sectionNbr: String): Seq[K] = {
    sections.filter(s => {(s.n == sectionNbr) || (s.n startsWith sectionNbr + "(")})
  }

  def rulesTree(ruleNbr: String): Seq[K] = {
    rules.filter(s => {(s.n == ruleNbr) || (s.n startsWith ruleNbr + "(")})
  }

  def ancestors(e: String): List[String] = {
    // Returned list includes itself
    val i = e.lastIndexOf("(")
    if (i == -1) {
      List(e)
    } else {
      e :: ancestors(e.substring(0, i))
    }
  }

  def ruleDescendants(ruleNumber: String): Seq[String] = {
    // Returned list includes itself
    ruleNumbers.filter(n => n == ruleNumber || n.startsWith(s"$ruleNumber("))
  }

  def sectionDescendants(sectionNumber: String): Seq[String] = {
    // Returned list includes itself
    sectionNumbers.filter(n => n == sectionNumber || n.startsWith(s"$sectionNumber("))
  }

  def init() {
    var lastTitle = ""
    sections.foreach({
      case K(n, Some(title), _, _) => sectionTitles(n) = title; lastTitle = title; sectionNumbers += n
      case K(n, None, _, _) => sectionTitles(n) = s"[$lastTitle]"; sectionNumbers += n
    })
    rules.foreach({
      case K(n, Some(title), _, _) => ruleTitles(n) = title; lastTitle = title; ruleNumbers += n
      case K(n, None, _, _) => ruleTitles(n) = s"[$lastTitle]"; ruleNumbers += n
    })
    sectionRules.foreach({
      case Pair(sectionNo, ruleNo) =>
        for (s <- ancestors(sectionNo) ++ sectionDescendants(sectionNo)) {
          if (sectionToRules.contains(s)) {
            if (!sectionToRules(s).contains(ruleNo))
              sectionToRules(s) :+= ruleNo
          } else
            sectionToRules(s) = mutable.Buffer(ruleNo)
        }
        for (r <- ancestors(ruleNo) ++ ruleDescendants(ruleNo)) {
          if (ruleToSections.contains(r)) {
            if (!ruleToSections(r).contains(sectionNo))
              ruleToSections(r) :+= sectionNo
          } else
            ruleToSections(r) = mutable.Buffer(sectionNo)
        }
    })
  }

  val ruleToSections = mutable.Map.empty[String, Seq[String]]
  val sectionToRules = mutable.Map.empty[String, Seq[String]]

  val sectionNumbers = mutable.Buffer.empty[String]
  val ruleNumbers = mutable.Buffer.empty[String]
  // Titles as displayed in search-result lists
  val sectionTitles = mutable.Map.empty[String, String]
  val ruleTitles = mutable.Map.empty[String, String]

}
